import React, { useEffect } from 'react';
import styles from './index.less';
import jingdong from '../../assets/jingdong.png';

const { BMap } = window;
// 信息窗口
const getInfoWindow = (map, item) => {
  const opts = {
    width: 250, // 信息窗口宽度
    height: 100, // 信息窗口高度
    title: item.name, // 信息窗口标题
    message: item.message,
  };
  const detailData = `<div>${item.message}
  <img style='width:100px;' src=${jingdong} alt=""/>
  </div>`;
  const infoWindow = new BMap.InfoWindow(detailData, opts); // 创建信息窗口对象
  map.openInfoWindow(infoWindow, map.getCenter()); // 打开信息窗口
};
export default () => {
  // 自定义点位
  const drawPoint = (map, item) => {
    const opt = {
      position: new BMap.Point(item?.data_real_time.baidu_lat, item?.data_real_time.baidu_lng),
      offet: new BMap.Size(30, -30),
    };
    const labal = new BMap.Label(`<div class=${styles.round_shape}>${item.name}</div>`, opt);
    labal.setStyle({
      background: 'none',
      border: 'none',
    });
    labal.addEventListener('click', () => {
      getInfoWindow(map, item);
    });
    map.addOverlay(labal);
  };

  const init = (map) => {
    const dataList = [
      {
        id: 1001,
        name: '用户01',
        message: '用户01',
        data_real_time: {
          baidu_lat: 118.805191,
          baidu_lng: 32.064735,
        },
      },
      {
        id: 1002,
        name: '用户02',
        message: '用户01',
        data_real_time: {
          baidu_lat: 119.063615,
          baidu_lng: 32.175805,
        },
      },
      {
        id: 1002,
        name: '用户02',
        message: '用户02',
        data_real_time: {
          baidu_lat: 118.918736,
          baidu_lng: 32.079666,
        },
      },
      {
        id: 1003,
        name: '用户03',
        message: '用户01',
        data_real_time: {
          baidu_lat: 118.864119,
          baidu_lng: 32.030947,
        },
      },
    ];
    dataList.forEach((item) => {
      // 创建地图实例
      const point = new BMap.Point(118.805191, 32.064735);
      // // 创建点坐标
      map.centerAndZoom(point, 15);
      const markerOpt = {
        title: '标题',
      };
      map.enableScrollWheelZoom(true);
      const marker = new BMap.Marker(
        new BMap.Point(item?.data_real_time.baidu_lat, item?.data_real_time.baidu_lng),
        markerOpt,
      );
      map.addOverlay(marker);
      drawPoint(map, item);
    });
  };
  useEffect(() => {
    const map = new BMap.Map('container');
    init(map);
  }, []);

  return (
    <div>
      地图01
      <div id="container" style={{ height: '100vh' }}></div>
    </div>
  );
};
